package com.jycrm.presentation.core.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jycrm.util.CrmProperities;

public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = -7285627034646932884L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doStream(request, response);
	}

	private void doStream(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String root = CrmProperities.rootfolder == null ? ""
				: CrmProperities.rootfolder;

		String absoluteFile = root + getPath(request);
		String fileName = this.getFileName(request);
		BufferedInputStream in = null;
		ServletOutputStream out = null;
		FileInputStream stream = null;
		

		try {
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName + "\"");
			out = response.getOutputStream();
			File file = new File(absoluteFile);
			stream = new FileInputStream(file);
			in = new BufferedInputStream(stream);
			int bytesRead = 0;
			final int length = 8192;
			byte[] buffer = new byte[length];
			while ((bytesRead = in.read(buffer, 0, length)) != -1) {
				// write at server side
				out.write(buffer, 0, bytesRead);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	private String getPath(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		String requestURI = request.getRequestURI();
		String path = null;
		int length = 0;
		if (contextPath != null) {
			length += contextPath.length();
		}
		if (servletPath != null) {
			length += servletPath.length();
		}
		if (requestURI != null && requestURI.length() >= length) {
			path = requestURI.substring(length, requestURI.length());
		}
		return path;
	}

	private String getFileName(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		String fileName = "";
		if (requestURI != null && requestURI.length() > 0) {
			String[] s = requestURI.split("/");
			fileName = s[s.length - 1];
		}
		return fileName;
	}

}
